package com.pn.controller;

import com.pn.entity.CurrentUser;
import com.pn.entity.Result;
import com.pn.entity.Role;
import com.pn.entity.dto.AssignAuthDto;
import com.pn.page.Page;
import com.pn.service.AuthService;
import com.pn.service.RoleAuthService;
import com.pn.service.RoleService;
import com.pn.utils.TokenUtils;
import com.pn.utils.WarehouseConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/role")
@RestController
public class RoleController {

    @Autowired
    private RoleService roleService;
    @Autowired
    private TokenUtils tokenUtils;
    @Autowired
    private RoleAuthService roleAuthService;

    @RequestMapping("/role-list")
    public Result roleList() {
        return Result.ok(roleService.queryAllRole());
    }

    @RequestMapping("/role-page-list")
    public Result roleList(Page page, Role role) {
        page = roleService.queryRoleByPage(page, role);
        return Result.ok(page);
    }

    @RequestMapping("/role-add")
    public Result addRole(@RequestBody Role role, @RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String token) {
        CurrentUser currentUser = tokenUtils.getCurrentUser(token);
        role.setCreateBy(currentUser.getUserId());
        return roleService.addRole(role);
    }


    @RequestMapping("/role-update")
    public Result updateRoleDescByRid(@RequestBody Role role, @RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String token) {
        CurrentUser currentUser = tokenUtils.getCurrentUser(token);
        role.setUpdateBy(currentUser.getUserId());
        return roleService.setRoleDescByRid(role);
    }

    @RequestMapping("/role-delete/{roleId}")
    public Result deleteRoleByRid(@PathVariable Integer roleId) {
        return roleService.removeRoleByRid(roleId);
    }

    @RequestMapping("/role-state-update")
    public Result updateRoleStateByRid(@RequestBody Role role, @RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String token) {
        CurrentUser currentUser = tokenUtils.getCurrentUser(token);
        role.setUpdateBy(currentUser.getUserId());
        return roleService.setRoleStateByRid(role);
    }

    // 查询角色拥有的权限url接口
    @RequestMapping("/role-auth")
    public Result roleAuthByRid(Integer roleId) {
        return Result.ok(roleAuthService.authIdsByRid(roleId));
    }

    // 给角色分配权限的url接口
    @RequestMapping("/auth-grant")
    public Result grantAuth(@RequestBody AssignAuthDto assignAuthDto) {
        roleAuthService.assignAuth(assignAuthDto);
        return Result.ok("分配权限成功！");
    }
}
